package com.free.semantic.web.interceptor;

import com.free.semantic.web.annotation.RequireAuth;
import com.free.semantic.web.security.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是方法处理器，直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 获取方法上的注解
        RequireAuth methodAnnotation = handlerMethod.getMethodAnnotation(RequireAuth.class);
        // 获取类上的注解
        RequireAuth classAnnotation = handlerMethod.getBeanType().getAnnotation(RequireAuth.class);

        // 如果方法和类上都没有注解，不需要验证
        if (methodAnnotation == null && classAnnotation == null) {
            return true;
        }

        // 从请求头获取token
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Missing or invalid token");
            return false;
        }

        token = token.substring(7); // 去掉 "Bearer " 前缀

        // 验证token
        if (!jwtUtil.validateToken(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Invalid token");
            return false;
        }

        // 从token中获取用户ID并设置到ThreadLocal
        Long userId = jwtUtil.getUserIdFromToken(token);
        JwtUtil.setCurrentUserForTest(userId);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后清除ThreadLocal中的用户ID
        JwtUtil.clearCurrentUserId();
    }
} 